package com.lj.universalframework.receiver

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import android.util.Log
import com.lj.universalframework.BuildConfig
import com.lj.universalframework.enum.NetworkChanges
import com.lj.universalframework.enum.NetworkStatus
import com.lj.universalframework.enum.NetworkType
import com.lj.universalframework.utils.NetworkChangeUtils
import java.net.InetSocketAddress
import java.net.Socket
import kotlin.concurrent.thread

/**
 * @ClassName NetworkChangeReceiver
 * @Description 广播监听网络变化
 * @Author LJ
 * @Date 2022/9/23 10:05
 * @Version 1.0
 */
class NetworkChangeReceiver : BroadcastReceiver() {

    companion object {
        const val ANDROID_NET_CHANGE_ACTION = "android.net.conn.CONNECTIVITY_CHANGE"
    }

    //当前网络连接状态
    private var networkStatus: NetworkStatus? = null

    //当前网络类型
    private var networkType: NetworkType? = null

    //当前网络变化
    private var networkChanges: NetworkChanges? = null

    override fun onReceive(context: Context?, intent: Intent?) {
        try {
            intent?.apply {
                if (!action.equals(ANDROID_NET_CHANGE_ACTION, ignoreCase = true)) return
                //获取手机所有连接管理对象
                context?.getSystemService(Context.CONNECTIVITY_SERVICE)?.apply {
                    (this as ConnectivityManager).apply {
                        //获取描述当前网络对象属性（能力）的 NetworkCapabilities 对象
                        val capabilities = getNetworkCapabilities(activeNetwork)
                        if (capabilities == null) {
                            //未连接
                            updateNetworkStatus(NetworkStatus.DISCONNECT, NetworkType.NO_NETWORK)
                            return
                        }
                        if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
                            //移动网络
//                            if (capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)){
//                                NetworkStatus.CONNECT
//                            }else{
//                                NetworkStatus.CONNECT_NO_NETWORK
//                            }
                            updateNetworkStatus(
                                NetworkStatus.CONNECT,
                                NetworkType.MOBILE_NETWORK
                            )
                            return
                        } else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
                            //wifi
                            updateNetworkStatus(NetworkStatus.CONNECT, NetworkType.WIFI_NETWORK)
                            return
                        } else {
                            //未知
                            updateNetworkStatus(
                                if (capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)){
                                    NetworkStatus.CONNECT
                                }else{
                                    NetworkStatus.CONNECT_NO_NETWORK
                                },
                                NetworkType.UNKNOWN_NETWORK
                            )
                            return
                        }
                    }
                }
            }
        } catch (e: Exception) {
            e.message
        }
    }


    /**
     * 更新网络状态
     * @param networkStatusUns 当前网络连接状态
     * @param networkTypeUns 当前网络类型
     */
    private fun updateNetworkStatus(networkStatusUns: NetworkStatus, networkTypeUns: NetworkType?) {
        when (networkStatusUns) {
            NetworkStatus.CONNECT -> {
                //连接
                when (networkTypeUns) {
                    NetworkType.MOBILE_NETWORK -> {
                        //移动网络
                        when (networkType) {
                            NetworkType.MOBILE_NETWORK -> {}
                            NetworkType.WIFI_NETWORK -> {
                                //WIFI
                                networkChanges = NetworkChanges.WIFI_MOVE
                            }
                            NetworkType.UNKNOWN_NETWORK -> {
                                //未知
                                networkChanges = NetworkChanges.UNKNOWN_MOVE
                            }
                            NetworkType.NO_NETWORK -> {
                                //无
                                networkChanges = NetworkChanges.NONE_MOVE
                            }
                            else -> {
                                //初始移动网络
                                networkChanges = NetworkChanges.MOBILE_NETWORK
                            }
                        }
                    }
                    NetworkType.WIFI_NETWORK -> {
                        //WIFI网络
                        when (networkType) {
                            NetworkType.MOBILE_NETWORK -> {
                                //移动
                                networkChanges = NetworkChanges.MOVE_WIFI
                            }
                            NetworkType.WIFI_NETWORK -> {}
                            NetworkType.UNKNOWN_NETWORK -> {
                                //未知
                                networkChanges = NetworkChanges.UNKNOWN_WIFI
                            }
                            NetworkType.NO_NETWORK -> {
                                //无
                                networkChanges = NetworkChanges.NONE_WIFI
                            }
                            else -> {
                                //初始WIFI
                                networkChanges = NetworkChanges.WIFI_NETWORK
                            }
                        }
                    }
                    NetworkType.UNKNOWN_NETWORK -> {
                        //未知网络
                        when (networkType) {
                            NetworkType.MOBILE_NETWORK -> {
                                //移动
                                networkChanges = NetworkChanges.MOVE_UNKNOWN
                            }
                            NetworkType.WIFI_NETWORK -> {
                                //WIFI
                                networkChanges = NetworkChanges.WIFI_UNKNOWN
                            }
                            NetworkType.NO_NETWORK -> {
                                //无
                                networkChanges = NetworkChanges.NONE_UNKNOWN
                            }
                            NetworkType.UNKNOWN_NETWORK -> {}
                            else -> {
                                //初始未知网络
                                networkChanges = NetworkChanges.UNKNOWN_NETWORK
                            }
                        }
                    }
                    NetworkType.NO_NETWORK -> {
                        //无网络
                        when (networkType) {
                            NetworkType.MOBILE_NETWORK -> {
                                //移动
                                networkChanges = NetworkChanges.MOVE_NONE
                            }
                            NetworkType.WIFI_NETWORK -> {
                                //WIFI
                                networkChanges = NetworkChanges.WIFI_NONE
                            }
                            NetworkType.NO_NETWORK -> {}
                            NetworkType.UNKNOWN_NETWORK -> {
                                //未知
                                networkChanges = NetworkChanges.UNKNOWN_NONE
                            }
                            else -> {
                                //初始无网络
                                networkChanges = NetworkChanges.NO_NETWORK
                            }
                        }
                    }
                    else -> {}
                }
            }
            NetworkStatus.DISCONNECT -> {
                //断开
                when (networkType) {
                    NetworkType.MOBILE_NETWORK -> {
                        //移动-无
                        networkChanges = NetworkChanges.MOVE_NONE
                    }
                    NetworkType.WIFI_NETWORK -> {
                        //WIFI-无
                        networkChanges = NetworkChanges.WIFI_NONE
                    }
                    NetworkType.UNKNOWN_NETWORK -> {
                        //未知-无
                        networkChanges = NetworkChanges.UNKNOWN_NONE
                    }
                    else -> {
                        //初始无网络
                        networkChanges = NetworkChanges.NO_NETWORK
                    }
                }
            }
            else -> {}
        }
        if (networkStatusUns != NetworkStatus.DISCONNECT) {
            //这里虽然是连接状态，但并不清楚是否连接的这个网络有网，进一步检测一下
            thread {
                if (isNetworkOnline()) {
                    networkStatus = networkStatusUns
                    networkType = networkTypeUns
                    //通知
                    NetworkChangeUtils.mInstance.notifyUpdate(
                        networkStatus,
                        networkType,
                        networkChanges
                    )
                    LogUtils(
                        "网络状态发生变化了：networkStatus:${networkStatus?.type}  networkType:${networkType?.type}  networkChanges:${networkChanges?.type}"
                    )
                    return@thread
                }
                this.networkStatus = NetworkStatus.CONNECT_NO_NETWORK
                this.networkType = networkTypeUns
                //通知
                NetworkChangeUtils.mInstance.notifyUpdate(
                    networkStatus,
                    networkType,
                    networkChanges
                )
                LogUtils("网络状态发生变化了：networkStatus:${networkStatus?.type}  networkType:${networkType?.type}  networkChanges:${networkChanges?.type}")
                return@thread
            }
            return
        }
        this.networkStatus = networkStatusUns
        this.networkType = networkTypeUns
        //通知
        NetworkChangeUtils.mInstance.notifyUpdate(
            networkStatus,
            networkType,
            networkChanges
        )
        LogUtils("网络状态发生变化了：networkStatus:${networkStatus?.type}  networkType:${networkType?.type}  networkChanges:${networkChanges?.type}")
    }

    /**
     * 检查当前网络是否有网
     * 耗时操作，不能放在Ui线程中
     * @return Boolean true 有网 false 无网络
     */
    private fun isNetworkOnline(): Boolean {
        try {
            Socket().connect(InetSocketAddress("8.8.8.8", 53), 3000)
            LogUtils("isNetworkOnline:有网")
            return true
        } catch (e: Exception) {
            e.message
        }
        LogUtils("isNetworkOnline:无网络")
        return false
    }

    private fun LogUtils(text: String) {
        if (!BuildConfig.DEBUG) return
        Log.i("测试一下", text)
    }
}